<template>
  <div id="main" class="container">
    <div class="inner-box">
      <Chat ref="chat" :robotMode="robotMode" @changeMode="changeMode" :leftUser="customerService"></Chat>
      <div class="mask" v-if="waiting">
        <div>
          <i class="el-icon-loading" />
          <div>正在等待客服</div>
          <div class="cancel" @click="changeMode">取消</div>
        </div>
      </div>
      <transition name="el-fade-in">
        <div v-show="!visitorInfoReady" class="visitor-info">
          <div class="signup-head">
            请输入您的联系信息
          </div>
          <ZshInput v-model="visitorInfo.name" placeholder="姓名" :error="errMsg.name"></ZshInput>
          <ZshInput v-model="visitorInfo.email" type="email" placeholder="电子邮件" :error="errMsg.email"></ZshInput>
          <ZshButton name="connect" :loading="loading" @click="updateVisitorInfo">立即接入</ZshButton>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import Chat from '@/components/chat'
import {getCustomerService,getVisitorInfo,updateVisitorInfo} from "@/api/service"
import {contactListeners} from "@/modules/im/command/listeners";
import {addListener} from "@/modules/im/command/base";
import Constants from "@/modules/im/constants";

import ZshInput from './components/zsh-input'
import ZshButton from './components/zsh-button'
import {connect, disconnect} from "@/api/im";
import {isEmail} from "@/libs/util"
import {getHistoryMessages} from "@/api/history";
import {findTenantById} from "../../api/tenant";
import {getHotList} from "../../api/knowledge";
import {mapActions} from 'vuex'

export default {
  name: "home",
  components:{Chat,ZshButton,ZshInput},
  data(){
    return {
      waiting:false,
      customerService:{},
      visitorInfoReady:true,
      visitorInfo:{},
      errMsg:{},
      loading:'',
      robotMode: true,
      tenantList: [],
      showTenantList: false,
      hotList:[]
    }
  },
  created() {
    let tenantId = this.$route.query['tenantId']
    console.log('tenantId: ' + tenantId)
    if(tenantId) {
      findTenantById(tenantId).then(res => {
        this.$store.commit('updateTenantInfo',res.data)
        this.initVisitor(tenantId)
        window.document.title = res.data.name + '客服'
        addListener(contactListeners,'Chat',this.handleContactMsg)
        getCustomerService({visitorId:this.$store.state.userInfo.visitorId,tenantId:tenantId}).then(res => {
          if(res.code == 200) {
            this.customerService = res.data
            this.$refs.chat.clearMsg()
            this.robotMode = false
            this.waiting = false
            this.addContact(res.data)
            connect()
          }else {
            getHotList(tenantId).then(res => {
              this.hotList = res.data
            })
          }
        }).finally(function (){

        })
      })
    }else {
      this.$router.replace({path:'/'})
      return
    }
  },
  methods:{
    initVisitor(tenantId) {
      getVisitorInfo({visitorId:this.$store.state.userInfo.visitorId,tenantId:tenantId}).then(res => {
        if(res.code == 200) {
          this.$store.commit('updateVisitorInfo',res.data)
          let check = this.checkVisitorInfo(res.data)
          if(!check) {
            this.visitorInfoReady = false
          }else{
            this.visitorInfoReady = true
          }
        }
      })
    },
    changeMode() {
      this.robotMode = !this.robotMode
      if(!this.robotMode) {
        this.waiting = true
        this.connect()
      }else{
        try {
          disconnect()
        }catch (e) {
          console.log(e)
        }
        this.waiting = false
      }
    },
    handleContactMsg(obj){
      console.log(obj)
      let cmd = obj[Constants.Contact.PROPERTY_CMD_TYPE]
      let payload = obj[Constants.Contact.PROPERTY_PAYLOAD]
      switch (cmd) {
        case Constants.Contact.CMD_REMOVE_CONTACT:
          this.removeContact(payload)
          break
        case Constants.Contact.CMD_ADD_CONTACT:
          this.addContact(payload)
          break
        default:
          break
      }
    },
    removeContact(obj) {
      if(obj == this.$store.state.userInfo.visitorId) {
        this.$message.success('本次客服已结束，您可以继续等待接入或者退出')
        this.waiting = true
        this.customerService = {}
      }
    },
    addContact(obj) {
      this.$message.success('为您成功接入客服：' + obj.nickname)
      this.customerService = obj
      this.$refs.chat.clearMsg()
      this.robotMode = false
      this.waiting = false
      getHistoryMessages({contactId:obj.contactId,start:0}).then(res => {
        if(res.code == 200) {
          this.$refs.chat.handleChatMessages(res.data)
        }
      })
    },
    checkVisitorInfo(visitor) {
      if(visitor.email == null || visitor.name == null) {
        return false
      }
      return true
    },
    updateVisitorInfo(){
      this.errMsg = {}
      if(this.visitorInfo.name == null || this.visitorInfo.name.trim().length == 0) {
        this.errMsg.name = '请输入姓名'
        return
      }
      if(!isEmail(this.visitorInfo.email)) {
        this.errMsg.email = '请输入有效邮箱'
        return
      }
      this.visitorInfo.tenantId = this.$store.state.tenantId
      this.visitorInfo.visitorId = this.$store.state.userInfo.visitorId
      this.loading = 'connect'
      updateVisitorInfo(this.visitorInfo).then(res => {
        if(res.code == 200) {
          this.$store.commit('updateVisitorInfo',res.data)
          this.loading = ''
          this.visitorInfoReady = true
        }
      })
    },
    connect(){
      connect()
      getCustomerService({visitorId:this.$store.state.userInfo.visitorId,tenantId:this.$store.state.tenantId}).then(res => {
        if(res.code == 200) {
          this.addContact(res.data)
        }
      }).finally(function (){

      })
    }
  },
  watch:{

  }
}
</script>

<style scoped lang="less">
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .inner-box {
    position: relative;
    width: 100%;
    max-width: 640px;
    min-width: 300px;
    height: 80%;
    box-shadow: 0px 0px 50px #A9B2BB;

    .visitor-info {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 2;
      padding: 50px;
      background: #FFF;
      .signup-head {
        font-size: 21px;
        margin: 40px 0;
        text-align: left;
      }
    }

    .mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1;
      background: rgba(0,0,0,.2);
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      color: #FFF;
      i {
        font-size: 26px;
      }
      .cancel {
        font-size: 14px;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}

@media(max-width: 679px) {
  .container {
    .inner-box {
      width: 100%;
      height: 100%;
    }
  }
}


</style>
